package com.example.datajdbc;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.util.Assert;

import com.example.datajdbc.model.LegoSet;
import com.example.datajdbc.model.Manual;
import com.example.datajdbc.repository.LegoSetRepository;
import com.example.datajdbc.support.Output;

@SpringBootApplication
public class JdbcApplication {

    public static void main(final String[] args) {
        SpringApplication.run(JdbcApplication.class, args);
    }

    @Bean
    public CommandLineRunner complexBusiness(final LegoSetRepository repository) {
        return args -> {
            // first LegoSet
            final LegoSet smallCar = this.creatLegoSet("Small Car 01");
            smallCar.setManual(new Manual("Jens Schauder", "Just put all the pieces together in the right order"));
            smallCar.addModel("suv", "SUV with sliding doors.");
            smallCar.addModel("roadster", "Slick red roadster.");
            repository.save(smallCar);

            Assert.notNull(smallCar.getId(), "smallCar doesn't have id");
            Assert.notEmpty(repository.findById(smallCar.getId()).get().getModels(), "smallCar doesn't have models");

            Output.list(repository.findAll(), "Original LegoSet");

            smallCar.setManual(new Manual("Jens Schauder", "One last attempt: Just build a car! Ok?"));
            repository.save(smallCar);

            Output.list(repository.findAll(), "Manual replaced");

            // second LegoSet
            final LegoSet bigCar = this.creatLegoSet("Big Car 01");
            repository.save(bigCar);

            Output.list(repository.findAll(), "Multiple query");

            Output.singleton(repository.findFirstByModelsContaining("road"), "LegoSet found");
        };
    }

    private LegoSet creatLegoSet(final String name) {
        final LegoSet legoSet = new LegoSet();
        legoSet.setName(name);
        return legoSet;
    }

}
